/**
 * 
 */
package org.springframework.data.redis.util;

import java.util.HashSet;
import java.util.Set;
import io.redisearch.Document;
import io.redisearch.Query;
import io.redisearch.Schema;
import io.redisearch.SearchResult;
import io.redisearch.client.Client;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/** 
* @version:v1.0
* @Description: 
* @author: jzhao
* @date: 2019年12月16日下午6:36:42
*/

public class JRediSearchClient {

    public static final String ip = "121.40.28.19";
    public static final int port = 63791;
    public static final String psw = "psw";

	public static void main(String[] args) {
        // 初始化客户端
        //Client client = new Client("myIndex5", "101.132.243.52", 63790);


        testBaseTag(false);

        testTag(false);

        //userId2c99ae7c7be32afd017be33029c00004,mTypenull,isDefault0,page0,size2,sortCREATETIME: DESC
        testTagQuery("MailAddr","@field:{ userId2c99ae7c7be32afd017be33029c00004 }");
    }

    private static Map<String, Object> createDocument(String title, String body, Integer price){
        Map<String, Object> fields = new HashMap<String, Object>();
        fields.put("title", title);
        fields.put("body", body);
        fields.put("star", price);
        return fields;
    }

    private static void printResult(SearchResult result) {
        List<Document> documentList = result.docs;
        for (Document document : documentList) {
        	
        	
        	System.out.println(document.getId());
            System.out.println(document.toString());
        }
    }
    
    private static void delResult(SearchResult result,Client client) {
        List<Document> documentList = result.docs;
        for (Document document : documentList) {
        	
        	
        	System.out.println(document.getId());
            //System.out.println(document.toString());
        	client.deleteDocuments(true, document.getId());
        }
    }

    /**
     * 纯搜索
     * @param index
     * @param searchTag 例如：@field:{ userId1 }
     */
    private static void testTagQuery(String index,String searchTag) {
    	Client client = new Client(index, ip, port,30,10,psw);
    	//client = new Client("myIndex", Pool<Jedis> pool)   ;    

        
        // 搜索 "any", 并且 star 数目在 0 ~ 2000 的
//        System.out.println("search 'any', result:");
//        Query query = new Query("any").addFilter(new Query.NumericFilter("star", 0, 2000)).setWithScores().limit(0, 10);
//        SearchResult result = client.search(query);
//        printResult(result);

        // 搜索 "视频"
        System.out.println("\r\nsearch '"+index+"', result:");
        
        int getNum = 5;
        
        int offset = 0;
        
       // while(getNum>=5) {
        	//Query other = new Query(searchTag).limit(0, 5);

        Query other = new Query("@field:{ userId2c99ae7c7be32afd017be33029c00004 }").limit(0, 10);

            SearchResult result = client.search(other);


            printResult(result);

            //getNum = result.docs.size();
            
           // delResult(result,client);
            
          //  offset += getNum;
       // }
        
    }


    private static void testBaseTag(boolean needDrop) {
        Client client = new Client("myIndex5", ip, port,30,10,psw);


        // 定义一个索引模式
        Schema schema = new Schema().addTextField("title", 5.0).addTextField("body", 1.0).addNumericField("star");

        // 创建索引
        // client.dropIndex();

        if(needDrop) {
            //删除索引，好像会删除全部（true的情况）
            client.dropIndex(false);
        }



        try {
            Map<String, Object> result0 = client.getInfo();
            System.out.println(result0);
        } catch (redis.clients.jedis.exceptions.JedisDataException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            client.createIndex(schema, Client.IndexOptions.defaultOptions().Default());
        }



        // 向索引中添加文档
        Map<String, Object> fields1 = createDocument("any video", "视频", 1000);
        Map<String, Object> fields2 = createDocument("any chat", "即时通信", 500);
        Map<String, Object> fields3 = createDocument("any security", "安全", 10000);
        Map<String, Object> fields4 = createDocument("any video github", "视频项目", 10000);

        client.addDocument("doc1", fields1);
        client.addDocument("doc2", fields2);
        client.addDocument("doc3", fields3);
        client.addDocument("doc4", fields4);

        client.deleteDocument("doc11");

        // 搜索 "any", 并且 star 数目在 0 ~ 2000 的
        System.out.println("search 'any', result:");
        Query query = new Query("any").addFilter(new Query.NumericFilter("star", 0, 2000)).setWithScores().limit(0, 10);
        SearchResult result = client.search(query);
        printResult(result);

        // 搜索 "视频"
        System.out.println("\r\nsearch '视频', result:");
        Query other = new Query("视频").limitFields("body").limit(0, 10);
        result = client.search(other);
        printResult(result);
    }

    private static void testTag(boolean onlyquery) {
    	Client client = new Client("userIndex", ip, port,30,10,psw);
    	//client = new Client("myIndex", Pool<Jedis> pool)   ;    

        String tagSeparator = "&";
        if(!onlyquery) {
            // 定义一个索引模式
            Schema schema = new Schema().addTagField("field", tagSeparator);

            // 创建索引
            // client.dropIndex();

            client.dropIndex(true);

            client.createIndex(schema, Client.IndexOptions.Default());

            // 向索引中添加文档
//        Map<String, Object> fields1 = createDocument2 ("userId1,page0,size10");
//        Map<String, Object> fields2 = createDocument2 ("userId1,page1,size10");
//        Map<String, Object> fields3 = createDocument2 ("userId2,page0,size10");
//        Map<String, Object> fields4 = createDocument2 ("userId2,page1,size10");
//
//        client.addDocument("&userId=1&page=0&size=10", fields1);
//        client.addDocument("&userId=1&page=1&size=10", fields2);
//        client.addDocument("&userId=2&page=0&size=10", fields3);
//        client.addDocument("&userId=2&page=1&size=10", fields4);
            Random r = new Random();
            int tt = 10 * 10000;
            //tt = 10;
            tt = 10;
            for (int i = 0; i < tt; i++) {
                String istr = String.valueOf(i + 1);

                int size = 10;
                if (r.nextBoolean()) {
                    size = 20;
                }

                for (int j = 0; j < 10; j++) {
                    //Map<String, Object> fields1 = createDocument2("userId" + istr + ",page" + j + ",size" + size);
                    Map<String, Object> fields1 = createDocument2("userId" + istr + tagSeparator +"page" + j + tagSeparator+"size" + size);
                    client.addDocument("&userId=" + istr + "&page=" + j + "&size=" + size, fields1);
                }

            }
        }
        
        // 搜索 "any", 并且 star 数目在 0 ~ 2000 的
//        System.out.println("search 'any', result:");
//        Query query = new Query("any").addFilter(new Query.NumericFilter("star", 0, 2000)).setWithScores().limit(0, 10);
//        SearchResult result = client.search(query);
//        printResult(result);

        // 搜索 "视频"
        System.out.println("\r\nsearch '按field查询', result:");
        //@field:{ userId1 } @field:{ page1 } @field:{ size10 }
        Query other = new Query("@field:{ userId1 }").limit(0, 10);
        SearchResult result = client.search(other);
        printResult(result);
    }
    
    private static Map<String, Object> createDocument2(String field){
        Map<String, Object> fields = new HashMap<String, Object>();
        fields.put("field", field);
  
        return fields;
    }

}
